#include <unistd.h>
#include <curses.h>
#include <cdk/swindow.h>
#include <string>
#include "window.h"
#include "debug.h"
using std::string;
#define HEIGHT 20


void Backspace(WINDOW* w) {
  int x,y;
  getyx(w,y,x);
  FCALL( mvwdelch(w,y,x-1) == ERR, "Failed to delch");
  FCALL( wrefresh(w) == ERR, "Failed to refresh");
}

void SetupWindows( ChatWindows &cw ) {
  FCALL( NULL == initscr(), "Failed to initialize screen");
  FCALL( cbreak() == ERR, "Failed to cbreak");
  FCALL( keypad( stdscr, TRUE ) == ERR, "Failed to setup keypad");
  FCALL( (cw.wt = newwin( HEIGHT, COLS, 0,0)) == NULL, 
      "Failed to create new window");
  FCALL( (cw.wb = newwin( HEIGHT, COLS, HEIGHT,0)) == NULL,
      "Failed to create new window");
  FCALL( (cw.sc = initCDKScreen(cw.wt)) == NULL,
      "Failed to initialize CDKScreen");
  FCALL( (cw.sw = newCDKSwindow( cw.sc,0,0,
      HEIGHT,COLS,(char*)TITLE, LOG, true, false)) == NULL,
      "Failed to create CDKSwindow");
}

void CloseWindows( ChatWindows &cw ) {
  destroyCDKSwindow( cw.sw );
  destroyCDKScreen( cw.sc );
  FCALL( delwin(cw.wb) == ERR, "Failed to destroy window.");
  FCALL( delwin(cw.wt) == ERR, "Failed to destroy window.");
  FCALL( endwin() == ERR, "Failed to end initialize terminal");
}

const char* GetString( ChatWindows & cw, int ch ) {
  static string str;
  static string ret;
  if( ch == '\b' || ch == KEY_BACKSPACE) {
    if( str.size() > 0 ) {
      Backspace(cw.wb);
      str.erase(str.end()-1);
    }
  }
  else if ( ch == '\n' ) {
    refreshCDKScreen( cw.sc );
    ret = str;
    str.clear();
    FCALL( wclear( cw.wb ) == ERR, "Failed to clear");
    FCALL( wprintw(cw.wb,PS1) == ERR, "Failed to print");
    FCALL( wrefresh( cw.wb ) == ERR, "Failed to refresh");
    return ret.c_str();
  }
  else {
    FCALL( waddch( cw.wb, ch ) == ERR, "Failed to write, waddch");
    str += (char) ch;
    FCALL( wrefresh(cw.wb) == ERR, "Failed to refresh");
  }
  return NULL;
}
int Activate( ChatWindows &cw, int ch ) {
  if( ch == KEY_UP || ch == KEY_DOWN || ch == KEY_RIGHT
      || ch == KEY_LEFT ) {
    activateCDKSwindow( cw.sw, NULL);
    return 1;
  }
  return 0;
}

void RefreshAll( ChatWindows &cw ) {
  refreshCDKScreen( cw.sc );
  FCALL( wrefresh(cw.wb) == ERR, "Failed to refresh");
} 
